package cn.zifangsky.license;

import java.io.File;

import org.apache.tools.ant.types.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 在项目启动时安装证书
 *
 * @author zifangsky
 * @date 2018/4/24
 * @since 1.0.0
 */

public class LicenseCheckListener implements ApplicationListener<ContextRefreshedEvent> {
    public static Logger logger = LoggerFactory.getLogger(LicenseCheckListener.class);
	private final String webRootPath = LicenseCheckListener.getWebRootAbsolutePath().substring(1, LicenseCheckListener.getWebRootAbsolutePath().length() - 1);

    @Value("${license.subject}")
    private String subject;
    
    @Value("${license.publicAlias}")
    private String publicAlias;
    
    @Value("${license.storePass}")
    private String storePass;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //root application context 没有parent
        ApplicationContext context = event.getApplicationContext().getParent();

        if(context == null){
        	  logger.info("++++++++ 开始安装证书 ++++++++");
              LicenseVerifyParam param = new LicenseVerifyParam();
              param.setSubject(subject);//证书subject
    	      param.setPublicAlias(publicAlias);// 公钥别称
    	      param.setStorePass(storePass);//访问公钥库的密码
              String scriptPath = File.separator+webRootPath + File.separator+"publicCerts.keystore";
              logger.info("/////////////////////////////////////////////////////////////////////////////////////////"+scriptPath);
              param.setPublicKeysStorePath(scriptPath);
              LicenseVerify licenseVerify = new LicenseVerify();
              //安装证书
              licenseVerify.install(param);

              logger.info("++++++++ 证书安装结束 ++++++++");
        }
    }
	// 得到WebRoot文件夹下的根路径，及web项目的根路径
	public static String getWebRootAbsolutePath() {
		String path = null;
		String folderPath = Path.class.getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		if (folderPath.indexOf("WEB-INF") > 0) {
			path = folderPath.substring(0, folderPath.indexOf("WEB-INF"));
		}
		if("\\".equals(File.separator)){   
			path = path.replace("/", "\\");
	     }
		  //linux下
		 if("/".equals(File.separator)){   
		   path = path.replace("\\", "/");
		 }
		return path;
	}

}
